<template>
  <div class="list">
    <div class="bg"></div>
    <van-cell-group class="group1" inset>
      <div class="headers">
        <div class="top">
          <img class="logo" src="../assets/logo.png" @click="$router.push('about')">
          <div class="local" @click="$router.push('about')">
            <img class="local_img" src="../assets/img/local.png">
            <div class="shop tov">{{ shop.address }}</div>
            <van-icon name="arrow" color="#9B9B9B" />
          </div>
          <van-button class="btn" type="default" size="small" @click="toPath('order')">我的订单</van-button>
        </div>
        <van-cell class="notice" title-class="tov" :title="`公告：${shop.notice}`" is-link @click="showNotice" :border="false" />
        <div class="search">
          <div class="search_wrap" @click="toPath('search')">
            <van-icon name="search" />
            <span>搜索</span>
          </div>
        </div>
      </div>
    </van-cell-group>

    <van-cell-group class="group2 main" inset>
      <div class="category">
        <van-sidebar v-model="activeKey" @change="onSidebarChange">
          <van-sidebar-item v-for="(item, index) in list" :key="index" :title="item.type_name" />
        </van-sidebar>
      </div>

      <div class="items" ref="list" @scroll.passive="handleScroll">
        <div class="item" v-for="(type, index) in list " :key="index" :id="`category_${index}`">
          <div class="title">{{ type.type_name }}</div>
          <van-card v-for="(item, index2) in type.product_list.length > 0 ? type.product_list : null " :key="index2" :desc="item.describe" :title="item.product_name">
            <template #thumb>
              <van-image class="thumb" :src="domain + item.imageurl" fit="cover" @click="openDetail(item)" />
            </template>
            <template #price>
              <div class="price">
                <span>￥</span>
                <span>{{ item.sale_price }}</span>
              </div>
            </template>
            <template #num>
              <van-stepper v-model="item.cart_number" :min="0" theme="round" :show-input="item.cart_number > 0 ? true : false" :show-minus="item.cart_number > 0 ? true : false" disable-input integer @plus="changeNumber(item, '+')" @minus="changeNumber(item, '-')" />
            </template>
          </van-card>
        </div>
      </div>
    </van-cell-group>

    <div class="cart">
      <div class="number">
        <van-badge class="cart_img" :content="cartNum > 0 ? cartNum : null" :max="99">
          <img src="../assets/img/cart.png" @click="showCart">
        </van-badge>
        <div v-if="cartNum" class="sum1" @click="showCart">
          <span><span>￥</span>{{ cartPirce }}</span>
          <span>免配送费</span>
        </div>
        <div v-else class="sum2">未选购商品</div>
      </div>
      <div class="submit" :class="cartNum ? 'is' : 'no'" @click="onSettlement">结算</div>
    </div>

    <van-popup class="popup" v-model="show" position="bottom" round>
      <div class="top">
        <div class="cart_name">餐品详情</div>
        <div class="del" @click="clearCartList">
          <van-icon name="delete-o" />
          <span>清空购物车</span>
        </div>
      </div>

      <!-- 购物车列表 -->
      <div class="cart_list">
        <van-card v-for="( item, index ) in cartList " :key="index" :desc="item.describe" :title="item.product_name">
          <template #thumb>
            <van-image class="thumb" :src="domain + item.imageurl" fit="cover" @click="openDetail(item)" />
          </template>
          <template #price>
            <div class="price">
              <span>￥</span>
              <span>{{ item.sale_price }}</span>
            </div>
          </template>
          <template #num>
            <van-stepper v-model="item.quantity" :min="0" theme="round" :show-input="item.quantity > 0 ? true : false" :show-minus="item.quantity > 0 ? true : false" disable-input integer @plus="changeCartNumber(item, '+')" @minus="changeCartNumber(item, '-')" />
          </template>
        </van-card>
      </div>
    </van-popup>

    <!-- 商品详情 -->
    <van-popup class="product" v-model="productShow" round closeable>
      <img class="thumb" :src="domain + obj.imageurl">
      <div class="obj">
        <div class="pname">{{ obj.product_name }}</div>
        <div class="pdesc">{{ obj.describe }}</div>
        <div class="pricenum">
          <div class="price">
            <span>￥</span>
            <span>{{ obj.sale_price }}</span>
            <span> /份</span>
          </div>
          <van-stepper v-model="obj.cart_number" :min="0" theme="round" :show-input="obj.cart_number > 0 ? true : false" :show-minus="obj.cart_number > 0 ? true : false" disable-input integer @plus="changeNumber(obj, '+')" @minus="changeNumber(obj, '-')" />
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { Dialog, Toast } from 'vant';
export default {

  data () {
    return {
      activeKey: 0,
      lastScrollTop: 0,
      isScrollHandling: false,
      list: [],
      cartList: [],
      obj: {},
      shop: {},
      cartNum: null,
      cartPirce: null,
      code: null,
      show: false,
      productShow: false,
    };
  },
  created () {
    this.getShopDetail()

    if (process.env.NODE_ENV === 'production') {
      if (this.$store.state.token == null) {
        this.getAuthorizeUrl()
      } else {
        this.getProductList()
        this.getCartList()
      }
    } else {
      this.getProductList()
      this.getCartList()
    }
  },
  methods: {
    // 获取授权链接
    getAuthorizeUrl () {
      this.$axios.get(this.$api.Authorize, {
        params: {
          url: window.location.href,
        }
      }).then((res) => {
        if (res.data.code == 1) {
          this.getWxCode(res.data.data.url)
        }
      })
    },
    // 微信授权
    getWxCode (url) {
      this.code = this.getUrlCode().code;
      //如果没有code 去获取code
      if (this.code == null) {
        window.location.href = url
      } else {
        // 通过微信授权的code登录系统
        this.$axios.post(this.$api.Authlogin, {
          code: this.code,
          state: 'STATE'
        }).then((res) => {
          if (res.data.code == 1) {
            this.$store.commit('setToken', res.data.data.token)
            this.getProductList()
            this.getCartList()
          } else {
            Toast('网络异常，请刷新重试')
          }
        })
      }
    },
    // 截取code
    getUrlCode () { // 截取url中的code方法
      var url = location.search
      var theRequest = new Object()
      if (url.indexOf("?") != -1) {
        var str = url.substr(1)
        var strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
          theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1])
        }
      }
      return theRequest
    },
    getShopDetail () {
      this.$axios.get(this.$api.shopinfo).then(res => {
        if (res.data.code == 1) {
          this.shop = res.data.data
          this.shop.notice = res.data.data.notice_text.replace(/<[^>]*>/g, '');
          this.$store.commit('setShop', this.shop)
        }
      })
    },
    getProductList () {
      this.$axios.get(this.$api.productlist).then(res => {
        if (res.data.code == 1) {
          this.list = res.data.data
        }
      })
    },
    getCartList () {
      this.$axios.get(this.$api.usercartlist).then(res => {
        if (res.data.code == 1) {
          this.cartList = res.data.data.cart
          this.cartNum = res.data.data.number
          this.cartPirce = res.data.data.amount
          if (this.cartList.length == 0) this.show = false
        }
      })
    },
    onSidebarChange (index) {
      this.activeKey = index;
      this.isScrollHandling = true;
      this.scrollToActiveCategory();
      this.$nextTick(() => {
        setTimeout(() => {
          this.isScrollHandling = false;
        }, 0);
      });
    },
    scrollToActiveCategory () {
      const targetElement = document.querySelector(`#category_${this.activeKey}`);
      if (targetElement) {
        this.$refs.list.scrollTop = targetElement.offsetTop;
      }
    },
    handleScroll () {
      if (this.isScrollHandling) return
      const scrollTop = this.$refs.list.scrollTop;
      this.lastScrollTop = scrollTop;
      let newActiveKey = null;
      const containerHeight = this.$refs.list.offsetHeight;
      const scrollHeight = this.$refs.list.scrollHeight;
      const isCloseToBottomThreshold = containerHeight * 0.2;
      const isNearBottom = scrollHeight - (scrollTop + containerHeight) < isCloseToBottomThreshold;

      for (let index = 0; index < this.list.length; index++) {
        const element = document.querySelector(`#category_${index}`);
        if (element && element.offsetTop <= scrollTop) {
          newActiveKey = index;
        } else {
          if (index === 0 && scrollTop === 0) continue;
          break;
        }
      }

      if (isNearBottom && newActiveKey === this.list.length - 2) newActiveKey = this.list.length - 1;

      if (newActiveKey !== null && newActiveKey !== this.activeKey) {
        this.isScrollHandling = true
        this.lastActiveKey = this.activeKey;
        if (!isNearBottom) this.activeKey = newActiveKey;
        this.$nextTick(() => {
          setTimeout(() => {
            this.$refs.list.scrollTop = this.lastScrollTop;
            this.isScrollHandling = false;
          }, 0);
        });
      }
    },
    showCart () {
      if (this.cartNum) {
        this.show = !this.show
      }
    },
    openDetail (e) {
      this.obj = e
      this.productShow = true
    },
    changeNumber (item, str) {
      let params = {
        product_id: item.product_id,
        quantity: str == '+' ? item.cart_number + 1 : item.cart_number - 1
      }
      let api = null
      if (params.quantity > 0 || params.quantity != "") {
        api = this.$api.usereditcart
      } else {
        api = this.$api.userdelcart
        params = {}
        params.cart_ids = item.cart_id.toString()
      }
      this.$axios.post(api, params).then(res => {
        if (res.data.code == 1) {
          this.getCartList()
          if (str == '+') {
            this.list.forEach(type => {
              if (type.type_id == item.type_id) {
                type.product_list.forEach(pro => {
                  if (pro.product_id == item.product_id) {
                    pro.cart_id = res.data.data
                  }
                });
              }
            });
          }
        } else {
          Toast.fail('操作失败')
          this.getProductList()
        }
      })
    },
    changeCartNumber (item, str) {
      let params = {
        product_id: item.product_id,
        quantity: str == '+' ? item.quantity + 1 : item.quantity - 1
      }
      let api = null
      if (params.quantity > 0 || params.quantity != "") {
        api = this.$api.usereditcart
      } else {
        api = this.$api.userdelcart
        params = {}
        params.cart_ids = item.cart_id.toString()
      }
      this.$axios.post(api, params).then(res => {
        if (res.data.code == 1) {
          this.getProductList()
          this.getCartList()
        } else {
          Toast.fail('操作失败')
          this.getCartList()
        }
      })
    },
    clearCartList () {
      let cart_ids = this.cartList.map(e => e.cart_id).toString()
      Dialog.confirm({
        message: '确认清空购物车？',
      }).then(() => {
        this.$axios.post(this.$api.userdelcart, { cart_ids }).then(res => {
          if ((res.data.code == 1)) {
            this.cartNum = null
            this.cartPrice = null
            this.getProductList()
            this.getCartList()
            this.show = false
          } else {
            Toast.fail(res.data.msg)
          }
        })
      }).catch(() => {
        // on cancel
      });
    },
    showNotice () {
      Dialog.alert({
        message: this.shop.notice_text,
        confirmButtonText: '我已知晓',
      }).then(() => {
        // on close
      });
    },
    onSettlement () {
      if (this.cartNum) {
        let ids = this.cartList.map(e => e.cart_id).toString()
        this.$router.push({ name: 'settlement', query: { ids } });
      } else {
        return false
      }
    },
    toPath (str) {
      if (this.$store.state.token) {
        this.$router.push({ name: str })
      } else {
        this.getAuthorizeUrl()
      }
    },
  },
}
</script>

<style lang="less" scoped>
.list {
  position: relative;
  padding-top: 5px;
  background-color: #EBEBEB;

  .bg {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    width: 100%;
    height: 85px;
    border-radius: 0 0 60px 60px;
    background-color: #DB5310;
  }

  .group1 {
    padding: 10px;
    margin: 0 9px 9px;
    border-radius: 6px;
    background-color: #fff;
  }

  .group2 {
    margin: 0 9px 9px;
    border-radius: 6px;
    background-color: transparent;
  }

  .headers {
    display: flex;
    flex-direction: column;
    height: 120px;
    box-sizing: border-box;

    .top {
      display: flex;
      justify-content: space-between;
      margin-bottom: 17px;

      .logo {
        width: 152px;
        height: 43px;
      }

      .local {
        display: flex;
        align-items: center;
        width: 110px;
        height: 47px;
        font-size: 14px;

        .local_img {
          width: 12px;
          height: 16px;
          margin-right: 7px;
        }

        .shop {
          width: 70px;
          color: #5F5F5F;
        }
      }

      .btn {
        padding: 6px;
        border-radius: 6px;
      }

    }

    .notice {
      padding: 0;
      color: #5F5F5F;
      font-size: 14px;
      margin-bottom: 10px;
    }

    .search {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      font-size: 14px;
      color: #5F5F5F;
      background-color: transparent;

      .search_wrap {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 26px;
        font-size: 14px;
        color: #BCBBBB;
        border-radius: 50px;
        background-color: #EDEDED;
      }
    }
  }

  .main {
    display: flex;
    height: calc(100vh - 5px - 120px - 20px - 9px);

    .category {
      width: 89px;
      height: inherit;
      margin-right: 12px;
      border-radius: 6px;
      background-color: #F3F3F3;
      overflow-y: auto;

      .van-sidebar {
        width: 89px;
        padding-bottom: 80px;

        .van-sidebar-item {
          color: #5F5F5F;
          font-size: 14px;
          padding: 12px;
          background-color: #F3F3F3;
        }

        .van-sidebar-item--select {
          color: #000;
          background-color: #fff;

          &::before {
            height: 28px;
            background-color: #DB5310;
          }
        }
      }
    }

    .items {
      position: relative;
      flex: 1;
      padding-bottom: 80px;
      overflow-y: auto;

      .item {
        padding: 10px 12px;
        margin-bottom: 10px;
        border-radius: 6px;
        background-color: #fff;

        .title {
          color: #5F5F5F;
          font-size: 14px;
        }
      }
    }
  }

  .cart {
    position: absolute;
    bottom: 15px;
    width: calc(100% - 30px);
    height: 55px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 0 15px;
    padding: 5px;
    border-radius: 50px;
    background-color: #494B4E;
    box-sizing: border-box;
    z-index: 9999;

    .cart_img {
      transform: translate(-20px, -10px);

      img {
        width: 78px;
        height: 78px;
      }

      /deep/ .van-badge {
        background-color: #DB5310;
      }

      /deep/ .van-badge--fixed {
        top: 30px;
        right: 20px;
      }
    }

    .number {
      display: flex;
      align-items: center;

      .sum1,
      .sum2 {
        color: #F3F3F3;
        font-size: 16px;
        transform: translateX(-16px);
      }

      .sum1 {
        display: flex;
        flex-direction: column;

        span:nth-child(1) {
          font-size: 16px;
          font-weight: bold;

          span {
            font-weight: 200;
          }
        }

        span:nth-child(2) {
          font-size: 10px;
        }
      }
    }

    .submit {
      width: 108px;
      height: 46px;
      line-height: 46px;
      color: #fff;
      font-size: 20px;
      text-align: center;
      border-radius: 50px;
    }

    .is {
      background-color: #DB5310;
    }

    .no {
      background-color: #9C9A9A;
    }
  }

  .tov {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
  }

  .van-card {
    padding: 0;
    background-color: #fff;
    margin-top: 10px;

    .van-card__thumb {
      width: 85px;
      height: 85px;
    }

    .thumb {
      width: 100%;
      height: 100%;
    }

    .van-card__title {
      color: #5F5F5F;
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 4px;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 1;
      -webkit-box-orient: vertical;
    }

    .price {
      color: #DB5310;

      span:nth-child(1) {
        font-size: 12px;
      }

      span:nth-child(2) {
        font-size: 16px;
        font-weight: bold;
      }
    }
  }

  .popup {
    height: 50%;
    padding: 16px 16px 86px;
    box-sizing: border-box;

    .top {
      display: flex;
      justify-content: space-between;
      margin-bottom: 16px;

      .cart_name {
        color: #000;
        font-size: 16px;
        font-weight: bold;
      }

      .del {
        color: #999999;
        font-size: 12px;

        .van-icon {
          margin-right: 4px;
        }
      }
    }

    .cart_list {
      height: 200px;
      overflow-y: auto;
    }
  }

  .product {
    width: 85%;
    border-radius: 6px;
    background-color: transparent;

    /deep/.van-popup__close-icon {
      top: 10px;
      right: 10px;
      padding: 4px;
      border-radius: 50%;
      background-color: #878787;
    }

    .thumb {
      display: block;
      width: 100%;
      height: 272px;
      object-fit: cover;
    }

    .obj {
      background-color: #fff;

      .pname {
        max-height: 55px;
        color: #5f5f5f;
        font-size: 16px;
        font-weight: bold;
        padding: 10px 12px 0;
        margin-bottom: 10px;
        overflow: hidden;
        box-sizing: border-box;
      }

      .pdesc {
        max-height: 95px;
        color: #5f5f5f;
        font-size: 14px;
        padding: 0 12px 10px;
        box-sizing: border-box;
        overflow-y: auto;
      }

      .pricenum {
        display: flex;
        justify-content: space-between;
        padding: 10px 12px;

        .price {
          span:nth-child(1) {
            color: #DB5310;
            font-size: 12px;
          }

          span:nth-child(2) {
            color: #DB5310;
            font-size: 18px;
            font-weight: bold;
          }

          span:nth-child(3) {
            color: #5F5F5F;
            font-size: 12px;
          }
        }
      }
    }
  }

  .van-popup--center {
    top: 45%;
  }
}
</style>